/*
 * @Author: wwj 3342930399@qq.com
 * @Date: 2024-03-05 19:13:30
 * @LastEditors: wwj 3342930399@qq.com
 * @LastEditTime: 2024-03-14 11:37:48
 * @FilePath: \vue\src\api\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import axios from "axios";
import { ShowError, ShowSuccess } from "@/utils/prompt";

export const baseURL = "http://localhost:9527"; // 项目的基路径
const request = axios.create({
  baseURL: baseURL,
  timeout: 60000,
  headers: {},
});

// axios 请求拦截器  interceptors  request
request.interceptors.request.use(
  function (config) {
    // 请求发送成功
    const token = localStorage.getItem("token") || "";
    config.headers.token = token; //传递token
    //ShowLoading();
    return config;
  },
  function (error) {
    console.log(error);
    //请求发送失败
    ShowError("网络异常");
    //return Promise.reject(error);
  }
);

// axios 响应拦截器  response
request.interceptors.response.use(
  function (response) {
    // 响应成功
    console.log(response.data);
    // Toast.clear();
    return response;
  },
  function (error) {
    console.log(error);
    // 响应失败
    ShowError("响应失败-未知错误");
    return Promise.reject(error);
  }
);

export const doGet = (url, params, headers) => {
  return new Promise((resolve, reject) => {
    request({
      method: "GET",
      url,
      params,
      headers,
    })
      .then((res) => {
        resolve(res); // 把axios 的 data 拆出去了
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export const doPost = (url, data, params, headers) => {
  return new Promise((resolve, reject) => {
    request({
      method: "POST",
      url,
      data,
      params,
      headers,
    })
      .then((res) => {
        resolve(res); // 把axios 的 data 拆出去了
      })
      .catch((err) => {
        reject(err);
      });
  });
};

export default request;
